// @db-cloud.js

import {
  getDiffTime,
  randomStr
} from '../util/util.js'

class DBPost {
  constructor(id) {
    this.id = id;
    this.db = wx.cloud.database();
  }
  //得到全部文章信息
  static async getAllPostData() {
    const db = wx.cloud.database();
    const res = await db.collection("post").get();
    return res.data;
  }

  // @db-cloud.js
  // 新增一条评论
  async newComment(comment) {
    comment.postId = this.id;
    await this.db.collection("comment").add({
      data: comment,
    });
    // 评论总数量+1
    this.addCommentNum();
  }

  //获取指定id号的文章数据
  async getPostItemById() {
    // 获取post实体
    const resPost = await this.db.collection("post")
      .doc(this.id).get();
    console.log(resPost)
    const post = resPost.data;

    // 获取用户对于当前post的收藏状态
    const status = await this.getUserLikeStatus();
    if (!status) {
      post.collectionStatus = false;
    } else {
      post.collectionStatus = status.collectionStatus;
    }
    return post;
  }
  async getUserLikeStatus() {
    const res = await this.db
      .collection("user_post")
      .where({
        postId: this.id,
      })
      .get();
    if (res.data.length === 0) {
      return null;
    } else {
      return res.data[0];
    }
  }

  async getCollectionNum(){
    const userPosts = await wx.cloud.callFunction({
      name:'getCollectionNum',
      data:{
        postId:this.id,
      }
    })
    console.log(userPosts.result.data)
    return userPosts.result.data
  }

  async collect() {
    const status = await this.getUserLikeStatus();
    console.log("status", status);

    //如果用户状态表未创建
    if (status === null) {
      this.db.collection("user_post").add({
        data: {
          postId: this.id,
          collectionStatus: true,
        },
      });
      this.addCollectionNum();
    } else {
      const _collectionStatus = status.collectionStatus;
      console.log(_collectionStatus);
      this.db
        .collection("user_post")
        .doc(status._id)
        .update({
          data: {
            collectionStatus: !_collectionStatus,
          },
        });
      console.log(_collectionStatus);
      if (_collectionStatus) {
        this.subtractCollectionNum();
      } else {
        this.addCollectionNum();
      }
    }
  }

  async getCommentData() {
    const res = await this.db.collection("comment")
      .where({
        postId: this.id
      }).get();
    console.log(res.data)
    const comments = res.data
    //按时间降序排列评论
    comments.sort(this.compareWithTime);
    var len = comments.length,
      comment;
    for (var i = 0; i < len; i++) {
      // 将comment中的时间戳转换成可阅读格式
      comment = comments[i];
      comment.create_time = getDiffTime(comment.create_time, true);
    }
    return comments;
  }

  compareWithTime(value1, value2) {
    var flag = parseFloat(value1.create_time) - parseFloat(value2.create_time);
    if (flag < 0) {
      return 1;
    } else if (flag > 0) {
      return -1
    } else {
      return 0;
    }
  }


  async uploadImgsToCloud(imgs, folderName) {
    let cloudIds = [];
    for (let img of imgs) {
      // 包装wx.getImageInfo成一个promise
      const info = await wx.getImageInfo({
        src: img,
      });
      // 获取一个随机名称
      const imgName = randomStr(36);
      const fullCloudPath = folderName + "/" + imgName + "." + info.type;

      const res = await wx.cloud.uploadFile({
        cloudPath: fullCloudPath,
        filePath: img,
      });
      cloudIds.push(res.fileID);
    }
    console.log(cloudIds);
    return cloudIds;
  }

  async uploadAudioToCloud(audio, folderName) {
    // 获取一个随机名称
    const audioName = randomStr(36);
    const format = audio.split(".").pop();
    const fullCloudPath = folderName + "/" + audioName + "." + format;
    const res = await wx.cloud.uploadFile({
      cloudPath: fullCloudPath,
      filePath: audio,
    });
    console.log(res);
    return res.fileID;
  }

  // 评论数量+1
  addCommentNum() {}
  // 阅读数量+1
  addReadingTimes() {}
  // 收藏数量 -1
  subtractCollectionNum() {}
  // 收藏数量 +1
  addCollectionNum() {}
}

export {
  DBPost
}